//全局的AJAX访问，处理AJAX清求时SESSION超时
$.ajaxSetup({
    contentType: "application/x-www-form-urlencoded;charset=utf-8",
    complete: function (XMLHttpRequest, textStatus) {
        // 通过XMLHttpRequest取得响应头，sessionstatus
        var res = XMLHttpRequest.responseJSON;
        if (typeof res != "undefined") {
            // 跳转的登录页面
            if (res.code === '101') {
                window.location.href = ctx + "/login";
            }
        }
    }
});

var BgOption = function (id, url, colums, queryParams, height) {
    this.id = id;
    this.url = url;
    this.method = "post";
    this.data = null;
    this.toolbarId = null;
    this.queryParams = queryParams;
    this.columns = colums;
    this.height = height;
    this.paginationType = "server";
    this.showColumns = false;
    this.showRefresh = false;
    this.pagination = true;
    this.onClickRow = null;
    this.onLoadSuccess = function (data) {

    }
}
/**
 * 初始化 Tree Table 的封装
 *
 * @author cyf
 */
var BSTreeTable = function (bstableId, url, columns) {
    this.btInstance = null;					// jquery和bootstrapTreeTable绑定的对象
    this.bstableId = bstableId;
    this.url = url;
    this.method = "post";
    this.columns = columns;
    this.data = {};// ajax的参数
    this.expandColumn = null;// 展开显示的列
    this.id = 'id';// 选取记录返回的值
    this.code = 'code';// 用于设置父子关系
    this.parentCode = 'pcode';// 用于设置父子关系
    this.expandAll = false;// 是否默认全部展开
    this.toolbarId = bstableId + "Toolbar";
    this.height = null;// 默认表格高度665
    this.onLoadSuccess = null;
};

BSTreeTable.prototype = {
    /**
     * 初始化bootstrap table
     */
    init: function () {
        var tableId = this.bstableId;
        this.btInstance =
            $('#' + tableId).bootstrapTreeTable({
                id: this.id,// 选取记录返回的值
                code: this.code,// 用于设置父子关系
                parentCode: this.parentCode,// 用于设置父子关系
                rootCodeValue: this.rootCodeValue,// 设置根节点code值----可指定根节点，默认为null,"",0,"0"
                type: this.method, // 请求数据的ajax类型
                url: this.url,   // 请求数据的ajax的url
                ajaxParams: this.data, // 请求数据的ajax的data属性
                expandColumn: this.expandColumn,// 在哪一列上面显示展开按钮,从0开始
                striped: true,   // 是否各行渐变色
                expandAll: this.expandAll,  // 是否全部展开
                columns: this.columns,		// 列数组
                toolbar: "#" + this.toolbarId,// 顶部工具条
                height: this.height,
                onLoadSuccess: this.onLoadSuccess
            });
        return this;
    },

    /**
     * 设置在哪一列上面显示展开按钮,从0开始
     */
    setExpandColumn: function (expandColumn) {
        this.expandColumn = expandColumn;
    },
    /**
     * 设置记录返回的id值
     */
    setIdField: function (id) {
        this.id = id;
    },
    getSelections: function () {
        var selected = this.btInstance.bootstrapTreeTable('getSelections');
        if (selected.length == 0) {
            return null;
        } else {
            return selected[0];
        }
    },
    /**
     * 设置记录分级的字段
     */
    setCodeField: function (code) {
        this.code = code;
    },
    setOnLoadSuccess: function (data) {
        this.onLoadSuccess = data;
    },
    /**
     * 设置记录分级的父级字段
     */
    setParentCodeField: function (parentCode) {
        this.parentCode = parentCode;
    },
    /**
     * 设置根节点code值----可指定根节点，默认为null,"",0,"0"
     */
    setRootCodeValue: function (rootCodeValue) {
        this.rootCodeValue = rootCodeValue;
    },
    /**
     * 设置是否默认全部展开
     */
    setExpandAll: function (expandAll) {
        this.expandAll = expandAll;
    },
    /**
     * 设置表格高度
     */
    setHeight: function (height) {
        this.height = height;
    },
    /**
     * 设置ajax post请求时候附带的参数
     */
    set: function (key, value) {
        if (typeof key == "object") {
            for (var i in key) {
                if (typeof i == "function")
                    continue;
                this.data[i] = key[i];
            }
        } else {
            this.data[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
        }
        return this;
    },

    /**
     * 设置ajax post请求时候附带的参数
     */
    setData: function (data) {
        this.data = data;
        return this;
    },

    /**
     * 清空ajax post请求参数
     */
    clear: function () {
        this.data = {};
        return this;
    },

    /**
     * 刷新表格
     */
    refresh: function (parms) {
        if (typeof parms != "undefined") {
            this.btInstance.bootstrapTreeTable('refresh', parms.query);// 为了兼容bootstrap-table的写法
        } else {
            this.btInstance.bootstrapTreeTable('refresh');
        }
    }
    ,
    onExpandAll: function () {
        this.btInstance.bootstrapTreeTable('expandAll');
    },
    onCollapseAll: function () {
        this.btInstance.bootstrapTreeTable('collapseAll');
    }
};

var BgdataTable = function () {
    this.idbst = null;
};
BgdataTable.prototype = {
    draw: function (option) {
        var op = {
            contentType: "application/x-www-form-urlencoded",
            url: option.url,				// 请求地址
            method: option.method,		// ajax方式,post还是get
            ajaxOptions: {				// ajax请求的附带参数
                data: option.data
            },
            striped: true,     			// 是否显示行间隔色
            cache: false,      			// 是否使用缓存,默认为true
            sortable: true,      		// 是否启用排序
            sortOrder: "desc",     		// 排序方式
            pageNumber: 1,      			// 初始化加载第一页，默认第一页
            pageSize: 10,      			// 每页的记录行数（*）
            pageList: [10, 20, 40],  	// 可供选择的每页的行数（*）
            queryParamsType: 'rows', 	// 默认值为 'limit' ,在默认情况下
            // 传给服务端的参数为：offset,limit,sort
            queryParams: function (param) {
                return $.extend(option.queryParams, param);
            }, // 向后台传递的自定义参数
            sidePagination: option.paginationType,   // 分页方式：client客户端分页，server服务端分页（*）
            search: false,      		// 是否显示表格搜索，此搜索是客户端搜索，不会进服务端
            strictSearch: true,			// 设置为 true启用 全匹配搜索，否则为模糊搜索
            showColumns: option.showColumns,     		// 是否显示所有的列
            showRefresh: option.showRefresh,     		// 是否显示刷新按钮
            minimumCountColumns: 2,    	// 最少允许的列数
            clickToSelect: true,    	// 是否启用点击选中行
            searchOnEnterKey: true,		// 设置为 true时，按回车触发搜索方法，否则自动触发搜索方法
            columns: option.columns,		// 列数组
            pagination: option.pagination,			// 是否显示分页条
            height: option.height,
            icons: {
                refresh: 'glyphicon-repeat',
                toggle: 'glyphicon-list-alt',
                columns: 'glyphicon-list'
            },
            iconSize: 'outline',
            onLoadSuccess: function (data) {
                option.onLoadSuccess(data);
            },
            responseHandler: function (res) {
                return res;
            },
            onClickRow: function (row, el, field) {
                if (option.onClickRow) {
                    option.onClickRow(row, el, field);
                }
            }
        };
        if (option.toolbarId) {
            op.toolbar = "#" + option.toolbarId;// 顶部工具条
        }
        this.idbst = $('#' + option.id).bootstrapTable(op);
        return this.idbst;
    },
    getSelections: function () {
        return this.idbst.bootstrapTable("getSelections");
    },
    load: function () {

    },
    refresh: function (params, pageNumber) {
        if (this.idbst) {
            if (typeof params != "undefined") {
                var data = {query: params};
                if (typeof pageNumber != "undefined" && pageNumber != null) {
                    data.pageNumber = pageNumber;
                }
                this.idbst.bootstrapTable("refresh", data);
            } else {
                this.idbst.bootstrapTable("refresh");
            }
        } else {
            this.draw();
        }
    }, destroy: function () {
        this.idbst.bootstrapTable("destroy");
        this.idbst = null;
    }
};
var cmm = function () {
    return {
        uuid: function () {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4"; // bits 12-15 of the time_hi_and_version field to
            // 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of
            // the
            // clock_seq_hi_and_reserved
            // to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        },
        strDgLen: function (v, f, len) {
            if (!len) {
                len = 10;
            }
            if (v.length > len) {
                f.push(v.substring(0, len));
                v = v.substring(len);
                cmm.strDgLen(v, f, len);
            } else {
                f.push(v);
            }
        },
        emptyVal: function (v) {
            if (v == null) {
                return "";

            }
            return v;
        },
        addRules: function (id) {
            $("#" + id).rules("add", {});
        },
        removeRules: function (id) {
            $("#" + id).rules("remove");
        },
        resetForm: function (id) {
            $("#" + id).resetForm();
        },
        layerMessge: function (content) {
            layer.open({
                type: 1,
                title: "提示",
                offset: "rb",
                time: 3000,
                shade: false,
                area: ["200px", "150px"],
                anim: 2,
                content: "<div style='text-align: center;color: red;width: 100%'>" + content + "</div>"
            });
        },
        resultAjax: {statusCode: "statusCode", message: "message"},
        ajax: function (url, data, type, dataType, success, timeout, error) {
            $.ajax({
                url: url,
                data: data,
                type: type,
                dataType: dataType,
                success: success,
                timeout: timeout,
                error: error
            })
        },
        confirm: function (msg, okCallback, cancelCallback) {
            var index = top.layer.confirm(msg, {title: ["确认", "font-size:14px;font-weight:bold;"]}, function () {
                okCallback();
                top.layer.close(index);
            }, cancelCallback);
        },
        layerLoad: function () {
            return layer.load(0, {shade: [0.1]});
        },
        layerClose: function (d) {
            layer.close(d);
        },
        strLen: function (v, len) {
            if (this.isNullorEmpty(v) && v.length > len) {
                return v.substring(0, len) + "..";
            }
            return v;
        },
        strTWLen: function (v, len) {
            if (this.isNullorEmpty(v) && v.length > (len + 3)) {
                return v.substring(0, len / 2) + "..." + v.substring(v.length - (len / 2));
            }
            return v;
        },
        fromData: function (dd, pre) {
            if (!pre) {
                pre = '';
            }
            for (var a in dd) {
                var o = $('#' + pre + a); // 重新查找元素
                if (o.length > 0) {
                    var v = eval('dd.' + a);
                    if (v && v != '') { // js中0被视为false
                        if (o.prop("nodeName").toLowerCase() == 'input') {
                            o.val(v);
                        }
                        if (o.prop("nodeName").toLowerCase() == 'textarea') {
                            o.val(v);
                        }
                    }
                }
            }
        },
        serializeObject: function (v) {
            var o = {};
            $.each(v.serializeArray(), function (index) {
                if (o[this["name"]]) {
                    o[this['name']] = o[this["name"]] + "," + this["value"];
                } else {
                    o[this['name']] = this["value"];
                }
            });
            return o;
        },
        serializeFormObject: function (tis) {
            var o = {};
            var a = tis.serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        },
        isNullorEmpty: function (v) {
            if (typeof v != undefined && v != null && v.length > 0) {
                return true;
            }
            return false;
        }, isNotNull: function (v) {
            if (typeof v != undefined && v != null) {
                return true;
            }
            return false;
        },
        isNUllZro: function (v) {
            if (v === null) {
                return 0;
            }
            return v;
        }
    }
}();